<?php

namespace jd_vop\response;

use jd_vop\exception\BizException;
use jd_vop\exception\DataException;
use Psr\Http\Message\ResponseInterface;

class Response
{
    public $success;
    public $resultMessage;
    public $resultCode;
    public $result;

    /**
     * @param $httpResponse ResponseInterface
     * @param $class
     * @throws DataException
     * @throws BizException
     */
    public function __construct(ResponseInterface $httpResponse, $class = null)
    {
        // 2. 数据错误
        $resp = json_decode($httpResponse->getBody()->getContents(), true);
//        var_dump($resp);
//        var_dump($httpResponse->getBody()->getContents());
        if (empty($resp)) {
            var_dump($httpResponse->getBody()->getContents());
            var_dump($resp);
            throw new DataException();
        }
        $this->success = $resp['success'] ?? false;
        $this->resultMessage = $resp['resultMessage'] ?? "";
        $this->resultCode = $resp['resultCode'] ?? "";
        // 3. 业务报错
        if (!$this->success) {
            var_dump($this->resultMessage);
            var_dump($this->resultCode);
            throw new BizException($this->resultMessage, $this->resultCode);
        }
        if (empty($class)) {
            $this->result = $resp['result'] ?? null;
        } else {
            $this->result = $class::parse($resp['result'] ?? []);
        }
        if (empty($resp['result']) && !empty($this->resultMessage)) {
            var_dump($this->resultMessage);
            var_dump($this->resultCode);
            throw new BizException($this->resultMessage, $this->resultCode);
        }

    }


}